<template>
	<div>
		<xn-form-container
			:title="formData.id ? '编辑' : '新增'"
			:width="1000"
			:visible="visible"
			:destroy-on-close="true"
			@close="onClose"
		>
			<a-form
				:wrapper-col="{ span: 16 }"
				:label-col="{ span: 8 }"
				autocomplete="off"
				labelAlign="right"
				ref="formRef"
				:model="formData"
				:rules="formRules"
			>
				<a-row>
					<a-col :span="12">
						<a-form-item label="销售方式" name="saleMethod">
							<a-select
								placeholder="请选择销售方式"
								:options="tool.dictList('saleMethod')"
								v-model:value="formData.saleMethod"
							>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="收入合同" name="contractId">
							<xn-page-selector
								ref="revenueContractRef"
								:page-function="
									(param) =>
										revenueContractApi.page(
											Object.assign(param, {
												types: '2,5'
											})
										)
								"
								v-model:value="formData.contractId"
								placeholder="请选择销售合同"
							>
							</xn-page-selector>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="项目名称">
							<a-input disabled v-model:value="formData.proInfoId" placeholder="请选择收入合同" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="客户名称" name="customerId">
							<xn-page-selector
								ref="customerRef"
								:field-names="{ label: 'custName', value: 'id' }"
								:page-function="(param) => customerApi.getPage(param)"
								v-model:value="formData.customerId"
								placeholder="请选择客户名称"
							>
							</xn-page-selector>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="备注" name="remark">
							<a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
						</a-form-item>
					</a-col>
				</a-row>

				<a-row>
					<a-col :span="24">
						<a-row>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-row>
						<a-table
							:row-selection="options.rowSelection"
							:pagination="false"
							:columns="goodsColumns"
							:data-source="formData.saleOrderDetailAddParamList"
							:scroll="{ x: 1000 }"
						>
							<template #bodyCell="{ index, record, column }">
								<template v-if="column.dataIndex === 'index'">
									<span>{{ index + 1 }}</span>
								</template>

								<template v-if="column.dataIndex === 'taxRate'">
									<a-input
										@input="taxRateChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.taxRate"
									/>
								</template>

								<template v-if="column.dataIndex === 'saleNum'">
									<a-input
										@input="orderNumChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.saleNum"
									/>
								</template>

								<template v-if="column.dataIndex === 'taxPrice'">
									<a-input
										@input="taxChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.taxPrice"
									/>
								</template>

								<template v-if="column.dataIndex === 'noTaxPrice'">
									<a-input
										@input="excludingTaxChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.noTaxPrice"
									/>
								</template>

								<template v-if="column.dataIndex === 'remark'">
									<a-input :style="{ width: column.width }" v-model:value="record.remark" />
								</template>
							</template>
						</a-table>
					</a-col>
				</a-row>

				<div style="margin-top: 15px">
					<span style="color: red; font-size: 18px; font-weight: bold">合计</span>
				</div>
				<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px">
					<a-col :span="6">
						<div style="padding-bottom: 10px">
							<span>销售数量</span>
						</div>
						<a-input disabled placeholder="0" v-model:value="saleNum" />
					</a-col>
					<a-col :span="6">
						<div style="padding-bottom: 10px">
							<span>含税总金额</span>
						</div>
						<a-input disabled placeholder="0" v-model:value="taxAmount" />
					</a-col>
					<a-col :span="6">
						<div style="padding-bottom: 10px">
							<span>不含税总金额</span>
						</div>
						<a-input disabled placeholder="0" v-model:value="noTaxAmount" />
					</a-col>
				</a-row>
			</a-form>

			<template #footer>
				<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
			</template>
		</xn-form-container>
		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
	</div>
</template>

<script setup name="dbsForm">
	import { required } from '@/utils/formRules'
	import productSelector from '@/components/Selector/productSelector.vue'
	import customerApi from '@/api/base_data/customerApi'
	import { message } from 'ant-design-vue'
	import { toRaw } from 'vue'
	import revenueContractApi from '@/api/contract/base/index'
	import saleorderApi from '@/api/sale/order/saleorderApi'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import tool from '@/utils/tool'
	import contractpurmaterialApi from '@/api/purchasing/order/contractpurmaterialApi'
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const productsRef = ref()
	const formRef = ref()
	const revenueContractRef = ref()
	const customerRef = ref()

	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const submitLoading = ref(false)
	const saleNum = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		formData.value = {}
		if (record) {
			saleNum.value = record.saleNum
			noTaxAmount.value = record.noTaxAmount
			taxAmount.value = record.taxAmount
			formData.value = { ...record }
			loadDetail(record)
		}

		nextTick(() => {
			customerRef.value.onPage({})
			revenueContractRef.value.onPage({})
		})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const removeGoods = () => {
		let datas = formData.value.saleOrderDetailAddParamList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['id'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		totalPurchases.value = totalOrderNum()
	}
	const selectedRowKeys = ref([])

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const orderNumChange = (record) => {
		let value = record.saleNum.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.saleNum = ''
		} else {
			record.saleNum = value
		}
		saleNum.value = totalOrderNum()
	}

	const taxRateChange = (record) => {
		let value = record.taxRate.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.taxRate = ''
		} else {
			record.taxRate = value
		}
	}
	const totalExcludingTaxTax = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['saleNum']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	const onProductChange = (items) => {
		let saleOrderDetailAddParamList = formData.value.saleOrderDetailAddParamList || []
		items.forEach((it) => {
			let find = saleOrderDetailAddParamList.find((item) => {
				return item['materialId'] == it['materialId']
			})
			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.saleOrderDetailAddParamList = items
	}

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '产品编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			width: 120,
			dataIndex: 'name',
			align: 'center',
			ellipsis: true
		},
		{
			title: '品牌',
			width: 100,
			dataIndex: 'brand',
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		saleMethod: [required('请选择销售方式')],
		contractId: [required('请选择合同')],
		customerId: [required('请选择客户')],
		settleMethod: [required('请选择结算方式')]
	}
	const addProduct = () => {
		if (!formData.value.saleOrderDetailAddParamList) {
			formData.value.saleOrderDetailAddParamList = []
		}
		productsRef.value.showDialog(formData.value.saleOrderDetailAddParamList)
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				let orderList = toRaw(formData.value.saleOrderDetailAddParamList) || []
				if (orderList.length <= 0) {
					message.error('请添加商品')
					return
				}
				let msg = null
				for (let i = 0; i < orderList.length; i++) {
					let it = orderList[i]
					if (!it['taxRate']) {
						msg = `第${i + 1}行税率不能为空!`
						break
					}
					if (!it['saleNum']) {
						msg = `第${i + 1}行销售数量不能为空!`
						break
					}
					if (!it['taxPrice']) {
						msg = `第${i + 1}行含税金额不能为空!`
						break
					}
					if (!it['noTaxPrice']) {
						msg = `第${i + 1}行不含税金额不能为空!`
						break
					}
				}
				if (msg) {
					message.error(msg)
					return
				}
				submitLoading.value = true
				let params = { ...formData.value }
				let products = params.saleOrderDetailAddParamList.map((it) => {
					return {
						materialId: it['materialId'],
						saleNum: it['saleNum'],
						taxRate: it['taxRate'],
						taxPrice: it['taxPrice'],
						noTaxPrice: it['noTaxPrice'],
						remark: it['remark']
					}
				})
				if (formData.id) {
					params.saleOrderDetailAddParamList = products
				} else {
					params.saleOrderDetailEditParamList = products
				}

				saleorderApi
					.addOrEdit(
						Object.assign(params, {
							type: '工程',
							saleNum: saleNum.value,
							taxAmount: taxAmount.value,
							noTaxAmount: noTaxAmount.value
						})
					)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.catch(() => {})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const loadDetail = (record) => {
		saleorderApi
			.detail({
				id: record.id
			})
			.then((res) => {
				let detailList = res.proSaleOrderDetailList
				detailList.forEach((it) => {
					it['remark'] = ''
					it['id'] = it['materialId']
					it['key'] = it['materialId']
				})
				formData.value.saleOrderDetailAddParamList = detailList
			})
			.catch(() => {})
	}

	const getOrderDetailList = (parameter) => {
		return contractpurmaterialApi
			.getPage(
				Object.assign(parameter, {
					contractId: formData.value.contractId
				})
			)
			.then((res) => {
				// res.records.forEach((it) => {
				// 	it['materialId'] = it['id']
				// 	it['key'] = it['id']
				// })
				// return res

				return {
					records: [
						{
							budgetDetailId: '1755843095724490753',
							budgetRemain: 200,
							budgetUnitPrice: 80,
							contractId: '1761394662879973377',
							createTime: '2024-02-24 22:16:27',
							createUser: '1543837863788879871',
							id: '1761394663005802497',
							key: '1761394663005802497',
							materialName: '物料名称',
							materialNum: '物料编码',
							brand: '品牌',
							code: '物料编码',
							unit: '单位',
							name: '物料名称',
							spec: '规格型号',
							remark: '',
							material: {
								brand: '品牌',
								code: '物料编码',
								costUnitPrice: 100,
								createTime: '2024-02-16 22:32:57',
								createUser: '1543837863788879871',
								deleteFlag: 'NOT_DELETE',
								id: '1758499712626483201',
								laborUnitPrice: 10,
								name: '物料名称',
								remark: '备注信息',
								spec: '规格型号',
								synUnitPrice: 30,
								unit: '单位',
								unitPrice: 20
							},
							materialId: '1758499712626483201',
							num: 100,
							total: 8000,
							unitPrice: 80
						}
					]
				}
			})
			.catch(() => {})
	}

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '产品编号',
			width: 120,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			dataIndex: 'name',
			width: 180,
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'unit',
			width: 100,
			align: 'center'
		},
		{
			title: '规格型号',
			dataIndex: 'spec',
			width: 120,
			align: 'center'
		},
		{
			title: '领料出库数量',
			dataIndex: 'saleNum',
			width: 120,
			align: 'center'
		},
		{
			title: '税率',
			dataIndex: 'taxRate',
			width: 120,
			align: 'center'
		},
		{
			title: '含税金额',
			dataIndex: 'taxPrice',
			width: 120,
			align: 'center'
		},
		{
			title: '不含税金额',
			dataIndex: 'noTaxPrice',
			width: 140,
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
